package com.zipou.framework.gwt.client.widget;

import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

public class MyTextBox extends TextBox  {

	private String originalValue = null;
	private String myStyle = null;

	public MyTextBox(String value) {  

		this.originalValue = value;
		super.setValue(originalValue);
		this.setStyleName("inputEmpty");

		class MyHandler implements ClickHandler, FocusHandler {

			@Override
			public void onClick(ClickEvent event) {
				focusValue();
			}

			@Override
			public void onFocus(FocusEvent event) {
				focusValue();

			}
		}

		MyHandler myHandler = new MyHandler();
		this.addFocusHandler(myHandler);
		this.addClickHandler(myHandler);

		class MyOtherHandler implements KeyUpHandler, BlurHandler {		


			@Override
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() > 48 && event.getNativeKeyCode() < 122  ){
					actionValue();
				}
			}

			@Override
			public void onBlur(BlurEvent event) {
				actionValue();
			}

		};

		MyOtherHandler myOtherHandler = new MyOtherHandler();
		this.addBlurHandler(myOtherHandler);
		this.addKeyUpHandler(myOtherHandler);

	}

	final public void setValue(String value) {
		super.setValue(value);
		actionValue();
	}

	final public void setOnError(Boolean b) {
		if (b) {
			this.myStyle = this.getStyleName();
			this.setStyleName("inputOnError");
		} else {
			this.setStyleName(myStyle);
		}
	}

	private void actionValue() {
		if(super.getValue().isEmpty()) {
			this.setStyleName("inputEmpty");
			super.setValue(originalValue);
		}else  {
			this.setStyleName("inputFull");
		}
	}

	private void focusValue() {
		if(super.getValue().equals(originalValue)) {
			this.setStyleName("inputFull");
			super.setValue("");
			RootPanel.get().getElement().focus();
		}		
	}

	@Override
	public String getValue() {
		String value = super.getValue();
		if((value.equals(this.originalValue)) || (value == null) || (value.equals(""))) {
			return null;
		} else { 
			return value;
		}
	}

}
